package com.example.m3u8app;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.m3u8.Downloader;
import com.m3u8.IDownloadCallback;
import com.m3u8.IDownloadService;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RequestExecutor;

import java.io.File;
import java.util.List;

/**
 * http://new.southtv.cn:9180/api/querypvr?gid=cctv13
 */
public class DownloadTsActivity extends AppCompatActivity {

    private IDownloadService mDownloadService;
    private TextView tv, tv_a;
    private TextView tv_1, tv_a_1;
    private ProgressBar pb, pb_a;
    private ImageView iv, iv_a;

    String url1 = "http://new.southtv.cn:9180/cctv13/pvr-08-15_22-00.m3u8";
    String url2 = "http://new.southtv.cn:9180/cctv13/pvr-08-16_01-36.m3u8";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);

        tv = findViewById(R.id.tv);
        tv_1 = findViewById(R.id.tv_1);
        pb = findViewById(R.id.pb);
        iv = findViewById(R.id.iv);

        tv_a = findViewById(R.id.tv_a);
        tv_a_1 = findViewById(R.id.tv_a_1);
        pb_a = findViewById(R.id.pb_a);
        iv_a = findViewById(R.id.iv_a);

        findViewById(R.id.tvQrCode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AndPermission.with(DownloadTsActivity.this)
                        .runtime()
                        .permission(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE
                        )
                        .rationale(new Rationale<List<String>>() {
                            @Override
                            public void showRationale(Context context, List<String> data, RequestExecutor executor) {

                            }
                        })
                        .onGranted(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                File file = new File(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_PICTURES), System.currentTimeMillis() / 1000 + "");
                                String basePath = file.getAbsolutePath();
                                String m3u8Path = basePath + File.separator + "午夜新闻.mp4";

                                Downloader.startDownload(DownloadTsActivity.this, url1, m3u8Path, basePath, "午夜新闻", serviceConnection);

                                String m3u8Path1 = basePath + File.separator + "全国主要城市天气预报.mp4";
                                Downloader.startDownload(DownloadTsActivity.this, url2, m3u8Path1, basePath, "全国主要城市天气预报", serviceConnection);
                            }
                        })
                        .onDenied(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                            }
                        })
                        .start();
            }
        });

        findViewById(R.id.bt_all_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Downloader.startAllDownload(getApplicationContext());
            }
        });

        findViewById(R.id.bt_all_pause).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Downloader.pauseAllDownload(getApplicationContext());
            }
        });

        iv.setTag("pause");
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iv.getTag().equals("pause")) {
                    iv.setImageResource(R.mipmap.player);
                    Downloader.pauseDownload(DownloadTsActivity.this, url1);
                    iv.setTag("player");
                } else {
                    iv.setImageResource(R.mipmap.pause);
                    Downloader.startDownload(DownloadTsActivity.this, url1);
                    iv.setTag("pause");
                }
            }
        });

        iv_a.setTag("pause");
        iv_a.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iv_a.getTag().equals("pause")) {
                    iv_a.setImageResource(R.mipmap.player);
                    Downloader.pauseDownload(DownloadTsActivity.this, url2);
                    iv_a.setTag("player");
                } else {
                    iv_a.setImageResource(R.mipmap.pause);
                    Downloader.startDownload(DownloadTsActivity.this, url2);
                    iv_a.setTag("pause");
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }

    /**
     * 启动binder
     */
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mDownloadService = IDownloadService.Stub.asInterface(service);
            if (mDownloadService != null) {
                Log.d("ttt", "ServiceConnection is OK");
                try {
                    mDownloadService.addDownloadCallback(mDownloadCallback);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("ttt", "onServiceDisconnected is OK");
            try {
                mDownloadService.removeDownloadCallback(mDownloadCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 启动IPC进程间通信
     */
    private IDownloadCallback mDownloadCallback = new IDownloadCallback.Stub() {

        @Override
        public void onStart(final String url) {
            Log.d("ttt", "onStart---" + url);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (url.equals(url1)) {
                        tv.setText(url + "---开始下载");
                    } else {
                        tv_a.setText(url + "---开始下载");
                    }
                }
            });
        }

        @Override
        public void onWait(final String url) throws RemoteException {
            Log.d("ttt", "onWait---" + url);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (url.equals(url1)) {
                        tv.setText(url + "---正在等待");
                    } else {
                        tv_a.setText(url + "---正在等待");
                    }
                }
            });
        }

        @Override
        public void onResume(final String url) throws RemoteException {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (url.equals(url1)) {
                        tv.setText(url + "---恢复下载");
                    } else {
                        tv_a.setText(url + "---恢复下载");
                    }
                }
            });
        }

        @Override
        public void onPause(final String url) throws RemoteException {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (url.equals(url1)) {
                        tv.setText(url + "---暂停下载");
                    } else {
                        tv_a.setText(url + "---暂停下载");
                    }
                }
            });
        }

        @Override
        public void onProcess(final String url, final int process) {
            Log.d("ttt", "onProcess---" + url + "---" + process);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (url.equals(url1)) {
                        tv.setText(url + "---正在下载");
                        tv_1.setText(process + "/100");
                        pb.setProgress(process);
                    } else {
                        tv_a.setText(url + "---正在下载");
                        tv_a_1.setText(process + "/100");
                        pb_a.setProgress(process);
                    }
                }
            });
        }

        @Override
        public void onComplete(final String url) {
            Log.d("ttt", "onComplete---" + url);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (url.equals(url1)) {
                        tv.setText(url + "---下载完成");
                        pb.setProgress(100);
                    } else {
                        tv_a.setText(url + "---下载完成");
                        pb_a.setProgress(100);
                    }
                }
            });
        }

        @Override
        public void onError(final String url) {
            Log.d("ttt", "onError---" + url);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (url.equals(url1)) {
                        tv.setText(url + "---下载失败");
                    } else {
                        tv_a.setText(url + "---下载失败");
                    }
                }
            });
        }

    };
}
